import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
class FileUploadService {
  /// 上传单张图片
  Future<Map<String, dynamic>> uploadImage(XFile imageFile) async {
    try {
      // 创建FormData
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imageFile.path,
          filename: imageFile.name,
        ),
      });

      // 调用上传接口 - 使用Dio实例直接调用
      final dio = Dio();
      
      // 获取token并设置headers
      final token = await _getToken();
      final headers = <String, dynamic>{
        'Content-Type': 'multipart/form-data',
      };
      if (token != null && token.isNotEmpty) {
        headers['Authorization'] = 'Bearer $token';
      }
      
      final response = await dio.post(
        '${_getBaseUrl()}/file/upload/oss',
        data: formData,
        options: Options(headers: headers),
      );

      if (response.data['code'] == 200) {
        return {
          'success': true,
          'data': response.data['data'],
          'message': '上传成功',
        };
      } else {
        return {
          'success': false,
          'data': null,
          'message': response.data['msg'] ?? '上传失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': null,
        'message': '上传失败: $e',
      };
    }
  }

  /// 批量上传图片
  Future<Map<String, dynamic>> uploadImages(List<XFile> imageFiles) async {
    try {
      List<String> uploadedUrls = [];
      List<String> failedFiles = [];

      for (int i = 0; i < imageFiles.length; i++) {
        final result = await uploadImage(imageFiles[i]);
        if (result['success']) {
          // 根据后端返回的数据结构提取URL
          final data = result['data'];
          String imageUrl;
          if (data is String) {
            imageUrl = data;
          } else if (data is Map && data['url'] != null) {
            imageUrl = data['url'];
          } else if (data is Map && data['fileName'] != null) {
            imageUrl = data['fileName'];
          } else {
            imageUrl = data.toString();
          }
          uploadedUrls.add(imageUrl);
        } else {
          failedFiles.add(imageFiles[i].name);
        }
      }

      if (failedFiles.isEmpty) {
        return {
          'success': true,
          'data': uploadedUrls,
          'message': '所有图片上传成功',
        };
      } else if (uploadedUrls.isNotEmpty) {
        return {
          'success': true,
          'data': uploadedUrls,
          'message': '部分图片上传成功，失败的文件: ${failedFiles.join(', ')}',
        };
      } else {
        return {
          'success': false,
          'data': [],
          'message': '所有图片上传失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': [],
        'message': '批量上传失败: $e',
      };
    }
  }

  // 获取 Token
  Future<String?> _getToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getString('access_token');
    } catch (e) {
      return null;
    }
  }

  // 获取 BaseUrl
  String _getBaseUrl() {
    if (kDebugMode) {
      return 'http://192.168.110.159:8080';
    } else {
      return 'http://118.196.25.232:8080';
    }
  }
}